package com.itheima.leetcode.od.c.stack;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <h3>栈数据合并/空栈压数</h3>
 * <h2>类似堆栈中的剩余数字</h2>
 */
public class StackMerging {
    static Stack<Integer> stack = new Stack<>();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] input = scanner.nextLine().split(" ");
        List<Integer> arr = new ArrayList<>();

        for (String num : input) {
            arr.add(Integer.parseInt(num));
        }

        // 逐个压入栈，并进行合并
        for (int num : arr) {
            stack.push(num);
            solve();
        }

        // 逆序输出栈中的元素
        List<Integer> result = new ArrayList<>();
        while (!stack.isEmpty()) {
            result.add(stack.pop());
        }

        System.out.println(result.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(" ")));
    }

    public static void solve() {
        // 处理相邻两个相等的元素合并
        if (stack.size() > 1
                && Objects.equals(stack.peek(), stack.get(stack.size() - 2))) {
            int num = stack.pop();
            stack.pop();
            stack.push(2 * num);
            solve(); // 递归调用，继续合并
        }
        // 处理连续多个元素的合并
        else if (stack.size() >= 3) {
            int sum = 0;
            for (int i = 0; i < stack.size() - 1; i++) {
                sum += stack.get(stack.size() - i - 2);
                if (sum >= stack.peek()) {
                    if (sum == stack.peek()) {
                        for (int j = 0; j < i + 2; j++) {
                            stack.pop();
                        }
                        stack.push(2 * sum);
                        solve(); // 递归继续合并
                    }
                    break;
                }
            }
        }
    }
}